<?php
/**
 * @file
 */

/**
 * Menu callback function
 */

function wordgame_admin_level_page($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;

  switch ($op) {
    case t('Create level'):
    case 'create':
      $build['level_create'] = drupal_get_form('wordgame_admin_level_edit');
      break;
    default:
      if (!empty($_POST['levels']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $build['wordgame_admin_level_multiple_delete_confirm'] = drupal_get_form('wordgame_admin_level_multiple_delete_confirm');
      }
      else {
        $build['wordgame_admin_level'] = drupal_get_form('wordgame_admin_level');
      }
  }
  return $build;
}

/**
 * Form callback function
 */

function wordgame_admin_level($form, &$form_state) {
  $header = array(
    'name' => array('data' => t('Name'), 'field' => 'name'),
    'max_guest' => array('data' => t('Max Guest')),
    'max_summon' => array('data' => t('Max Summon')),
    'max_point' => array('data' => t('Max Point')),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('wordgame_level', 'l');

  $count_query = clone $query;
  $count_query->addExpression('COUNT(l.lid)');

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('l', array('lid', 'name', 'max_guest', 'max_summon', 'max_point'))
    ->limit(50)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
  );
  $options = array();
  foreach (module_invoke_all('wordgame_level_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'unblock',
  );

  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();
  $options = array();
  foreach ($result as $level) {
    $options[$level->lid] = array(
      'name' => $level->name,
      'max_guest' =>  $level->max_guest,
      'max_summon' => $level->max_summon,
      'max_point' => $level->max_point,
      'operations' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => t('edit'),
          '#href' => "admin/config/wordgame/level/edit/$level->lid",
          '#options' => array('query' => $destination)
        )
      ),
    );
  }

  $form['levels'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No level available.'),
  );
  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Submit the user administration update form.
 */
function wordgame_admin_level_submit($form, &$form_state) {
  $operations = module_invoke_all('wordgame_level_operations', $form, $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['levels']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    }
    else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function wordgame_admin_level_validate($form, &$form_state) {
  $form_state['values']['levels'] = array_filter($form_state['values']['levels']);
  if (count($form_state['values']['levels']) == 0) {
    form_set_error('', t('No levels selected.'));
  }
}

function wordgame_admin_level_multiple_delete_confirm($form, &$form_state) {
  $edit = $form_state['input'];

  $form['levels'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  $lids = array_keys(array_filter($edit['levels']));
  $levels = wordgame_all_levels();
  foreach ($lids as $lid) {
    $level = $levels[$lid];

    $form['levels'][$lid] = array(
      '#type' => 'hidden',
      '#value' => $lid,
      '#prefix' => '<li>',
      '#suffix' => check_plain($level->name) . "</li>\n",
    );
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  return confirm_form($form,
    t('Are you sure you want to cancel these levels?'),
    'admin/config/wordgame/level', t('This action cannot be undone.'),
    t('Delete levels'), t('Cancel'));
}

/**
 * Submit handler for mass-account cancellation form.
 */
function wordgame_admin_level_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['levels'] as $lid => $value) {
      //db_delete('wordgame_level')->condition('lid', $lid)->execute();
    }
  }
  $form_state['redirect'] = 'admin/config/wordgame/level';
}

/**
 * Menu callback function
 */
function wordgame_admin_level_edit($form, &$form_state, $level = NULL) {
  $form['edit_level'] = array(
    '#type' => 'fieldset',
    '#title' => t('Level'),
    '#collapsible' => TRUE,
    '#tree' => TRUE
  );
  if ($level) {
    $levels = wordgame_all_levels();
    if (isset($levels[$level])) {
      $level = $levels[$level];
    }
    $form['edit_level']['lid'] = array(
      '#type' => 'hidden',
      '#value' => !empty($level->lid) ? $level->lid : 0
    );
  }
  $form['edit_level']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#default_value' => !empty($level->name) ? $level->name : ''
  );
  $form['edit_level']['max_guest'] = array(
    '#type' => 'textfield',
    '#title' => t('Max Guest'),
    '#required' => TRUE,
    '#default_value' => !empty($level->max_guest) ? $level->max_guest : 2
  );
  $form['edit_level']['max_summon'] = array(
    '#type' => 'textfield',
    '#title' => t('Max Summon'),
    '#required' => TRUE,
    '#default_value' => !empty($level->max_summon) ? $level->max_summon : 2
  );
  $form['edit_level']['max_point'] = array(
    '#type' => 'textfield',
    '#title' => t('Max points'),
    '#required' => TRUE,
    '#default_value' => !empty($level->max_point) ? $level->max_point : ''
  );
  $form['edit_level']['max_word'] = array(
    '#type' => 'textfield',
    '#title' => t('Max words'),
    '#required' => TRUE,
    '#default_value' => !empty($level->max_word) ? $level->max_word : 5
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  $form['cancel'] = array(
    '#type' => 'link',
    '#title' => t('Cancel'),
    '#href' => 'admin/config/wordgame/level'
  );
  return $form;
}

/**
 * Submit callback function
 */
function wordgame_admin_level_edit_submit($form, &$form_state) {
  $level = $form_state['values']['edit_level'];
  if (!empty($level['lid'])) {
    drupal_write_record('wordgame_level', $level, array('lid'));
  }
  else {
    drupal_write_record('wordgame_level', $level);
  }
  drupal_set_message(t('The level has been saved successful!'));
  drupal_goto('admin/config/wordgame/level');
}